<?php

namespace App\Console\Commands;

use App\Models\DayCollection;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Models\ParkRecord;
use App\Models\ParkInfo;

class CollectionFlow extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'collect:flow';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '汇聚车场流量';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $now = Carbon::now();
        $minute = floor($now->minute/10);
        $now->minute($minute*10)->second(0);
        $proTIme = Carbon::createFromTimestamp($now->getTimestamp())->subMinute(10);

        $parks = ParkInfo::active()->select('park_code')->get();

        $parks->map(function ($item) use ($now,$proTIme){
            $collection = DayCollection::firstOrNew(
                [
                    'park_code' => $item->park_code,
                    'hour' => $now
                ],
                [
                    'leave_flow' => 0,
                    'enter_flow' => 0
                ]
            );

            $table='t_park_record_'.$item->park_code;
            if(\Schema::connection('park_cloud')->hasTable($table)){

                $parkRecord =  new ParkRecord();
                $parkRecord->setTable($table);

                $collection['leave_flow'] = $parkRecord->where('out_time','>=',$proTIme->getTimestamp())
                    ->where('out_time','<',$now->getTimestamp())
                    ->count();

                $collection['enter_flow'] = $parkRecord->where('in_time','>=',$proTIme->getTimestamp())
                    ->where('out_time','<',$now->getTimestamp())
                    ->count();

                $collection['all_flow'] = $parkRecord->where('status','=',1)
                    ->count();
            }

            $collection->save();

        });

        $this->info('流量汇聚成功');

    }
}
